package ch.didierviret.memgest.server.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import ch.didierviret.memgest.shared.entities.PersonsGroup;

import com.google.appengine.api.datastore.Key;

public class PersonsGroupDAO {
	private EntityManager em;

	public PersonsGroupDAO() {
		em = EMF.get().createEntityManager();
	}

	public void finalize() {
		em.close();
	}

	public void delete(PersonsGroup e) {
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		e = em.merge(e);
		em.remove(e);
		tx.commit();
	}

	// TODO Delete all : Remove after testing ?
	public void deleteAll() {
		em.createQuery("DELETE FROM PersonsGroup").executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public List<PersonsGroup> findAll() {
		List<PersonsGroup> personsGroups = em.createQuery(
				"SELECT e FROM PersonsGroup e").getResultList();
		return personsGroups;
	}

	public PersonsGroup findByKey(Key key) {
		return em.find(PersonsGroup.class, key);
	}

	public PersonsGroup insert(PersonsGroup e) {
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		em.persist(e);
		tx.commit();
		return e;
	}

	public PersonsGroup update(PersonsGroup e) {
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		e = em.merge(e);
		tx.commit();
		return e;
	}
}
